package com.jhd.fuzhou.view.quantitative;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.GradeReportService;
import com.jhd.fuzhou.service.ProcessService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.EditTextView;
import com.jhd.fuzhou.util.SaveSupervisionInspection;
import com.jhd.fuzhou.util.TextDialog;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.MinorSpeciality;
import com.jhd.fuzhou.vo.PersonInfoVo;
import com.jhd.fuzhou.vo.Supervisor;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.DialogShow.dialogShow;
import static com.jhd.fuzhou.util.StartProcess.completeByAssignUpdate;
import static com.jhd.fuzhou.util.StartProcess.start;
import static com.jhd.fuzhou.util.TimeUtil.getTime;
import static com.jhd.fuzhou.util.TimeUtil.getTimeDialog;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class QuantitativeStepTwoActivity extends BaseActivity {
    @BindView(R.id.btn_next)
    Button btn_next;//下一步
    @BindView(R.id.btn_back)
    Button btn_back;//上一步
    @BindView(R.id.rel_startTime)
    RelativeLayout rel_startTime;//选择开始时间
    @BindView(R.id.rel_endTime)
    RelativeLayout rel_endTime;//选择结束时间
    @BindView(R.id.rel_specialityDetail)
    RelativeLayout rel_specialityDetail;//选择专业明细
    @BindView(R.id.tv_startTime)
    TextView tv_startTime;//显示开始时间
    @BindView(R.id.tv_endTime)
    TextView tv_endTime;//显示结束时间
    @BindView(R.id.tv_speciality)
    TextView tv_speciality;//显示所属专业
    @BindView(R.id.tv_specialityDetail)
    TextView tv_specialityDetail;//显示专业明细
    @BindView(R.id.tv_Supervisor_1)
    TextView tv_Supervisor_1;//显示监督员1
    @BindView(R.id.tv_Supervisor_2)
    TextView tv_Supervisor_2;//显示监督员2
    @BindView(R.id.rel_Supervisor_1)
    RelativeLayout rel_Supervisor_1;//选择监督员1
    @BindView(R.id.rel_Supervisor_2)
    RelativeLayout rel_Supervisor_2;//选择监督员2
    @BindView(R.id.et_inspectors)
    EditText et_inspectors;//输入陪同检查人员
    @BindView(R.id.et_managementAddress)
    EditText et_managementAddress;//输入检查地址
    @BindView(R.id.et_remark)
    EditText et_remark;//输入备注
    @BindView(R.id.iv_address_choose)ImageView iv_address_choose;//检查地址下拉图标
    private Context context = this;
    private List<Supervisor> supervisorList2 = new ArrayList<>();//将已经被选中的监督员去除
    private List<PersonInfoVo> personInfoVos;


    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_step_two);
    }

    @Override
    protected void processLogic() {
        application.addStepActivity(this);
        onBack();
        getTaskApproveLeve1();
        getSupervisorSelector(context);
        getAddressByUnitIdAndCredit(context);
        show();
    }

    private void show() {
        tv_speciality.setText(supervisionInspectionVo.getSpecialityCategory());
        EditTextView.TextViewChange(tv_speciality, context);
        tv_specialityDetail.setText(supervisionInspectionVo.getSpecialityDetail());
        EditTextView.TextViewChange(tv_specialityDetail, context);
        if(StringUtil.isNullOrEmpty(supervisionInspectionVo.getInspectStartTime()))supervisionInspectionVo.setInspectStartTime(getTime(new Date()));
        tv_startTime.setText( StringUtil.isNullOrEmpty(supervisionInspectionVo.getInspectStartTime()) ? "请选择": supervisionInspectionVo.getInspectStartTime());
        EditTextView.TextViewChange(tv_startTime,context);
        if(StringUtil.isNullOrEmpty(supervisionInspectionVo.getInspectEndTime()))supervisionInspectionVo.setInspectEndTime(getTime(new Date()));
        tv_endTime.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getInspectEndTime()) ? "请选择" : supervisionInspectionVo.getInspectEndTime());
        EditTextView.TextViewChange(tv_endTime, context);
        tv_Supervisor_2.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getSecondSupervisorName()) ? "请选择" : supervisionInspectionVo.getSecondSupervisorName());
        EditTextView.TextViewChange(tv_Supervisor_2, context);
        et_inspectors.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getAccompanyName()) ? (StringUtil.isNullOrEmpty(supervisionInspectionVo.getContactPerson()) ? "" : supervisionInspectionVo.getContactPerson()) : supervisionInspectionVo.getAccompanyName());
        et_managementAddress.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getInspectionLocation()) ? "": supervisionInspectionVo.getInspectionLocation());
        et_remark.setText(StringUtil.isNullOrEmpty(supervisionInspectionVo.getRemarks()) ? "" : supervisionInspectionVo.getRemarks());
        supervisionInspectionVo.setFirstSupervisorId((StringUtil.isNullOrEmpty(supervisionInspectionVo.getFirstSupervisorId())) ? application.getId() : supervisionInspectionVo.getFirstSupervisorId());
        supervisionInspectionVo.setFirstSupervisorName((StringUtil.isNullOrEmpty(supervisionInspectionVo.getFirstSupervisorName())) ? application.getName() : supervisionInspectionVo.getFirstSupervisorName());
        supervisionInspectionVo.setFirstSupervisorNo((StringUtil.isNullOrEmpty(supervisionInspectionVo.getFirstSupervisorNo())) ? application.getLawEnforceNo() : supervisionInspectionVo.getFirstSupervisorNo());
        supervisionInspectionVo.setSecondSupervisorId((StringUtil.isNullOrEmpty(supervisionInspectionVo.getSecondSupervisorId())) ? null : supervisionInspectionVo.getSecondSupervisorId());
        supervisionInspectionVo.setSecondSupervisorName((StringUtil.isNullOrEmpty(supervisionInspectionVo.getSecondSupervisorName())) ? null : supervisionInspectionVo.getSecondSupervisorName());
        supervisionInspectionVo.setSecondSupervisorNo((StringUtil.isNullOrEmpty(supervisionInspectionVo.getSecondSupervisorNo())) ? null : supervisionInspectionVo.getSecondSupervisorNo());
        tv_Supervisor_1.setText((StringUtil.isNullOrEmpty(supervisionInspectionVo.getFirstSupervisorName())) ? "请选择" : supervisionInspectionVo.getFirstSupervisorName());
        EditTextView.TextViewChange(tv_Supervisor_1, context);
        tv_Supervisor_2.setText((StringUtil.isNullOrEmpty(supervisionInspectionVo.getSecondSupervisorName())) ? "请选择" : supervisionInspectionVo.getSecondSupervisorName());
        EditTextView.TextViewChange(tv_Supervisor_2, context);
        if (supervisionInspectionVo.getBusinessStatus().equals("0")) {
            btn_next.setText("上传");
        }
    }

    @OnClick({R.id.btn_next, R.id.btn_back, R.id.rel_startTime, R.id.rel_endTime, R.id.rel_specialityDetail, R.id.rel_Supervisor_1, R.id.rel_Supervisor_2, R.id.et_inspectors, R.id.et_managementAddress, R.id.et_remark,R.id.iv_address_choose})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_next:
                if (tv_startTime.getText().toString().equals("请选择")) {
                    CustomToast.showText(context, "请选择检查开始时间!", 3000, 0, 0).show();
                    break;
                }
                if (tv_endTime.getText().toString().equals("请选择")) {
                    CustomToast.showText(context, "请选择检查结束时间!", 3000, 0, 0).show();
                    break;
                }
                if (tv_Supervisor_2.getText().toString().equals("请选择")) {
                    CustomToast.showText(context, "请选择监督员2!", 3000, 0, 0).show();
                    break;
                }
                if (et_inspectors.getText().toString().equals("")) {
                    CustomToast.showText(context, "请输入陪同检查人员!", 3000, 0, 0).show();
                    break;
                }
                if (et_managementAddress.getText().toString().equals("")) {//默认为经营地址
                    CustomToast.showText(context, "请输入检查地址!", 3000, 0, 0).show();
                    break;
                }
                supervisionInspectionVo.setAccompanyName(et_inspectors.getText().toString().trim());
                supervisionInspectionVo.setInspectionLocation(et_managementAddress.getText().toString().trim());
                supervisionInspectionVo.setRemarks(et_remark.getText().toString());
                supervisionInspectionVo.setInspectStartTime(tv_startTime.getText().toString());
                supervisionInspectionVo.setInspectEndTime(tv_endTime.getText().toString());
                if (supervisionInspectionVo.getBusinessStatus().equals("0")) {
                    btn_next.setClickable(false);
                    upload();
                } else {
                    startActivity(new Intent(context, QuantitativeStepThreeActivity.class));
                }
                break;
            case R.id.btn_back:
                onBackPressed();
                break;

            case R.id.et_inspectors:
                TextDialog.showDialog(context, "陪同检查人员", et_inspectors);
                break;
            case R.id.et_managementAddress:
                TextDialog.showDialog(context, "检查地址", et_managementAddress);
                break;
            case R.id.et_remark:
                TextDialog.showDialog(context, "备注说明", et_remark);
                break;
            case R.id.rel_startTime:
                getTimeDialog(1, tv_startTime, context);
                break;
            case R.id.rel_endTime:
                getTimeDialog(2, tv_endTime, context);
                break;
            case R.id.iv_address_choose:
                dialogShow(context,iv_address_choose,et_managementAddress,null,"检查地址",null,supervisedUnitVoList);
                break;
            case R.id.rel_Supervisor_1:
                if(supervisorList!=null){
                    supervisorList2.clear();
                    for (Supervisor supervisor : supervisorList) {
                        if(!tv_Supervisor_2.getText().toString().equals(supervisor.getName())){
                            supervisorList2.add(supervisor);
                        }
                    }
                    dialogShow(context,null,tv_Supervisor_1,tv_Supervisor_1,"监督员",supervisorList2,null);
                }else{
                    supervisorList=new ArrayList<>();
                    dialogShow(context,null,tv_Supervisor_1,tv_Supervisor_1,"监督员",supervisorList,null);
                }
                break;
            case R.id.rel_Supervisor_2:
                if(supervisorList!=null){
                    supervisorList2.clear();
                    for (Supervisor supervisor : supervisorList) {
                        if(!tv_Supervisor_1.getText().toString().equals(supervisor.getName())){
                            supervisorList2.add(supervisor);
                        }
                    }
                    dialogShow(context,null,tv_Supervisor_2,tv_Supervisor_1,"监督员",supervisorList2,null);
                }else{
                    supervisorList=new ArrayList<>();
                    dialogShow(context,null,tv_Supervisor_2,tv_Supervisor_1,"监督员",supervisorList,null);
                }
                break;

        }
    }

    /*上传表单*/
    public void upload(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        GradeReportService vs = retrofit.create(GradeReportService.class);
        Call<JsonForResult> jsonForResultCall = vs.saveGradeReportMst(application.getAccessToken(), SaveSupervisionInspection.saveQuantitative(supervisionInspectionVo,personInfoVos,application,0,0));
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(StringUtil.isNullOrEmpty(supervisionInspectionVo.getId())){
                            start(application,jsonForResult.getData().toString(),"量化分级",context);
                        }else{
                            completeByAssignUpdate(application,personInfoVos.get(0).getUserName(),supervisionInspectionVo.getTaskId(),"",null,supervisionInspectionVo.getId(),"未审核","修改成功",context);
                        }
                    }else{
                        CustomToast.showText(context,"添加量化分级失败！",3000,0,0).show();
                        btn_next.setClickable(true);
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                    btn_next.setClickable(true);
                }
            }
            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "上传失败!";
                UtilHelper.alertMsg(context, "错误", msg);
                btn_next.setClickable(true);
            }
        });
    }
    public void getTaskApproveLeve1(){
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("username",application.getName()).addParam("userId",application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getTaskApproveLeve1(application.getAccessToken(),params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if(jsonForResult.getData()!=null){
                            personInfoVos= JSON.parseArray(jsonForResult.getData().toString(), PersonInfoVo.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context,e.getLocalizedMessage(),3000,0,0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }
}